package jupiter.filters;

import java.util.regex.Matcher;

import jupiter.messaging.ApplicationAddressBook;
import jupiter.messaging.Inbox;
import jupiter.messaging.Message;
import jupiter.servlets.JabbifyServlet;
import jupiter.util.Timey;

import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Random;
import org.json.JSONException;

public class UserFilter {
	Logger logger = LoggerFactory.getLogger(UserFilter.class);
	public JSONObject create(Message message){
		Timey t = new Timey();
		HttpServletRequest req = message.getRequest();
		HttpSession session = req.getSession(true);
		session.setMaxInactiveInterval(JabbifyServlet.TIMEOUT_SECS+45);
		if( session.isNew() ){
			session.setMaxInactiveInterval(JabbifyServlet.TIMEOUT_SECS+45);
			message = escape_name_and_website(message);
			Inbox i = new Inbox(message,session);
			session.setAttribute("Inbox",i);
			if(i.is_banned == true)
				message.ban();
			if(i.is_registered == true)
				message.register();
			ApplicationAddressBook.addInbox(i);
		}
		message.stillSend();
		JSONObject sending = new JSONObject();
		try{
			sending.put("session_id", session.getId());
			return sending;
		}catch(JSONException e){
			logger.error("JSONException", e);
			return null;
		}finally{
			t.end("UserCreateFilter");
		}
	}
	public JSONObject read_only_create(Message message){
		Timey t = new Timey();
		HttpServletRequest req = message.getRequest();
		HttpSession session = req.getSession(true);
		session.setMaxInactiveInterval(JabbifyServlet.TIMEOUT_SECS+45);
		if( session.isNew() ){
			session.setMaxInactiveInterval(JabbifyServlet.TIMEOUT_SECS+45);
			Inbox i = new Inbox(message,session, true);
			i.call_id = random_string();
			logger.info("i.call_id: "+i.call_id);
			logger.info("i.page: "+i.page);
			logger.info("i.domain: "+i.domain());
			session.setAttribute("Inbox",i);
			ApplicationAddressBook.addInbox(i);
			if(i.is_registered == true)
				message.register();
		}
		JSONObject sending = new JSONObject();
		try{
			sending.put("session_id", session.getId());
			return sending;
		}catch(JSONException e){
			logger.error("JSONException", e);
			return null;
		}finally{
			t.end("UserReadOnlyCreateFilter");
		}
	}
	private String random_string(){
		Random random =  new Random();
        long r1 = random.nextLong();
        long r2 = random.nextLong();
        String hash1 = Long.toHexString(r1);
        String hash2 = Long.toHexString(r2);
        String hash = hash1 + hash2;
        return hash;
	}
	public JSONObject destroy(Message message){
		Timey t = new Timey();
		logger.info("User:delete");
		HttpServletRequest req = message.getRequest();
		if(req == null)	return new JSONObject();
		HttpSession session = req.getSession(false);
		if(session != null){
			Inbox i = (Inbox) session.getAttribute("Inbox");
			// close this user's jabbify long poll connection
			message.to = i.call_id;
			message.putInInboxes();
			logger.info("User:delete:"+session.getId());
			session.invalidate();
		}else{
			logger.info("User:delete:?");
		}
		JSONObject sending = new JSONObject();
		try{
			sending.put("session_id", session.getId());
			return sending;
		}catch(JSONException e){
			logger.error("JSONException", e);
			return null;
		}finally{
			t.end("UserDestroyFilter");
		}
	}
	public JSONObject update(Message message){
		HttpServletRequest req = message.getRequest();
		if(req == null)	return new JSONObject();
		HttpSession session = req.getSession(true);
		Inbox i = (Inbox) session.getAttribute("Inbox");
		message = escape_name_and_website(message);
		try{
			i.name = message.parsed.getString("name");
			i.website = message.parsed.getString("website");
			return null;
		}catch(JSONException e){
			logger.error("JSONException", e);
			return null;
		}
	}
	public Message escape_name_and_website(Message message){
		try{
			message.name = jupiter.filters.MessageFilter.escapeHTML((String) message.parsed.remove("name"));
			message.parsed.put("name", message.name);
			message.website = jupiter.filters.MessageFilter.escapeHTML((String) message.parsed.remove("website"));
			message.parsed.put("website", message.website);
			return message;
		}catch(JSONException e){
			logger.error("JSONException", e);
	    	return null;
		}
	}
}
